
/**************************************************/
const SEARCH_KEY = '__SEARCH__'
const SEARCH_GAME_KEY = '__SEARCH_GAME__'
const SEARCH_IDLE_KEY = '__SEARCH_IDLE__'
const USERINFO_KEY = '__USER_INFO__'

const SEARCH_MAX_LEN = 15

/**
 * 倒叙插入（匹配前置）
 * @param {*} arr 
 * @param {*} val
 * @param {*} compare
 * @param {*} maxLen
 */
function insertArray(arr, val, compare, maxLen) {
    const index = arr.findIndex(compare)
    if (index === 0) {
        return
    }
    if (index > 0) {
        arr.splice(index, 1)
    }
    arr.unshift(val)
    if (maxLen && arr.length > maxLen) {
        arr.pop()
    }
}

/**
 * 匹配删除
 * @param {*} arr
 * @param {*} compare
 */
function deleteFromArray(arr, compare) {
    const index = arr.findIndex(compare)
    if (index > -1) {
        arr.splice(index, 1)
    }
}



export function loadUserInfo() {
    return uni.getStorageSync(USERINFO_KEY) || {};
}
export function saveUserInfo(userinfo) {
	uni.setStorageSync(USERINFO_KEY, userinfo)
	return userinfo
}
export function clearUserInfo() {
    uni.removeStorageSync(USERINFO_KEY);
    return {}
}
/** ***************************** Search  剧本*********************************/


export function loadSearch() {
    return uni.getStorageSync(SEARCH_KEY) || [];
}
  
export function saveSearch(query) {
    let searches = uni.getStorageSync(SEARCH_KEY) || [];
    insertArray(searches, query, (item) => {
        return item === query
    }, SEARCH_MAX_LEN)    
    uni.setStorageSync(SEARCH_KEY, searches)
    return searches
}
  
export function clearSearch() {
    uni.removeStorageSync(SEARCH_KEY);
    return []
}

/** ***************************** Search  活动*********************************/


export function loadSearchGame() {
    return uni.getStorageSync(SEARCH_GAME_KEY) || [];
}
  
export function saveSearchGame(query) {
    let searches = uni.getStorageSync(SEARCH_GAME_KEY) || [];
    insertArray(searches, query, (item) => {
        return item === query
    }, SEARCH_MAX_LEN)    
    uni.setStorageSync(SEARCH_GAME_KEY, searches)
    return searches
}
  
export function clearSearchGame() {
    uni.removeStorageSync(SEARCH_GAME_KEY);
    return []
}

/** ***************************** Search  闲本*********************************/


export function loadSearchIdle() {
    return uni.getStorageSync(SEARCH_IDLE_KEY) || [];
}
  
export function saveSearchIdle(query) {
    let searches = uni.getStorageSync(SEARCH_IDLE_KEY) || [];
    insertArray(searches, query, (item) => {
        return item === query
    }, SEARCH_MAX_LEN)    
    uni.setStorageSync(SEARCH_IDLE_KEY, searches)
    return searches
}
  
export function clearSearchIdle() {
    uni.removeStorageSync(SEARCH_IDLE_KEY);
    return []
}
